package camera;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class NewSobel {
	public static BufferedImage apply(BufferedImage img) {
		BufferedImage newImg = new BufferedImage(img.getWidth(),
				img.getHeight(), BufferedImage.TYPE_INT_RGB);
		int[][] m = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
		for (int y = 1; y < img.getHeight() - 1; y++) {
			for (int x = 1; x < img.getWidth() - 1; x++) {
				Color c = new Color(img.getRGB(x, y));
				int cr = c.getRed();
				int cg = c.getGreen();
				int cb = c.getBlue();

				int rr = 0;
				int rg = 0;
				int rb = 0;

				for (int my = 0; my < 2; my++) {
					for (int mx = 0; mx < 2; mx++) {
						int mc = m[my][mx];
						if (mc != 0) {
							Color cm = new Color(img.getRGB(x + mx - 1, y + my
									- 1));
							rr += Math.abs(cm.getRed() - cr) * mc;
							rg += Math.abs(cm.getGreen() - cg) * mc;
							rb += Math.abs(cm.getBlue() - cb) * mc;
						}

						mc = m[mx][my];
						if (mc != 0) {
							Color cm = new Color(img.getRGB(x + mx - 1, y + my
									- 1));
							rr += Math.abs(cm.getRed() - cr) * mc;
							rg += Math.abs(cm.getGreen() - cg) * mc;
							rb += Math.abs(cm.getBlue() - cb) * mc;
						}
					}
				}

				rr = Math.abs(rr) / 6;
				rg = Math.abs(rg) / 6;
				rb = Math.abs(rb) / 6;

				newImg.setRGB(x, y, new Color(rr, rg, rb).getRGB());
			}
		}

		return newImg;
	}

	public static BufferedImage applyThreshold(BufferedImage img, int threshold) {
		BufferedImage newImg = new BufferedImage(img.getWidth(),
				img.getHeight(), img.getType());
		
		int WHITE = Color.WHITE.getRGB();
		for (int y = 1; y < img.getHeight() - 1; y++) {
			for (int x = 1; x < img.getWidth() - 1; x++) {
				Color c = new Color(img.getRGB(x, y));
				int cr = c.getRed();
				int cg = c.getGreen();
				int cb = c.getBlue();

				if (cr > threshold || cg > threshold || cb > threshold) {
					newImg.setRGB(x, y, WHITE);
				}
			}
		}

		return newImg;
	}

	public static void main(String[] args) throws IOException {
		BufferedImage img = ImageIO.read(CompareImage.class
				.getResource("/resource/lena.jpg"));

		ImageIO.write(applyThreshold(apply(img), 10), "png", new File("sobel.png"));
	}
}
